var request = require('superagent'),
  fs = require('fs'),
  cheerio = require('cheerio'),
  accounts = require('./config').accounts,
  crypto = require('crypto'),
  md5 = require('md5'),
  // task = require('./controller/task')
  later = require('later')

var headers = {
  Accept:
    'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  'Accept-Encoding': 'gzip, deflate, br',
  'Accept-Language':
    'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
  Connection: 'keep-alive',
  // 'Content-Type': 'application/x-www-form-urlencoded',
  Cookie: 'locale=zh-CN;',
  'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}

var passporturl = 'https://passport.bitmain.com',
  shopurl = 'https://shop.bitmain.com',
  urls = {
    login: passporturl + '/login',
    success: passporturl + '/success',
    orderdetal: shopurl + '/user/orderDetails.htm',
    addProd: shopurl + '/user/orderDetails.htm?m=add&count=1&fitting=&pid=',
    prodList: shopurl + '/main.htm?lang=zh',
    genOrder: shopurl + '/user/orderDetails.htm?m=y',
    orderConfirmBase: shopurl + '/user/orderConfirm.htm',
    orderConfirm: shopurl + '/user/orderConfirm.htm?m=y',
    validateImg: 'https://shop.bitmain.com/user/validateImage.jsp'
  }

var damaURL = 'http://v1-http-api.jsdama.com/api.php?mod=php&act=upload'

var LoginCookie = [],
  ShopCookie = []

function _rename(filename) {
  console.log('start rename Image: ' + filename)
  // var rs = fs.createReadStream(filename)
  // var hash = crypto.createHash('md5')
  // rs.on('data', hash.update.bind(hash))

  var _dig = ''
  var start = new Date().getTime()
  var md5sum = crypto.createHash('md5')
  // fs.readFile(filename, function(err, buf) {
  //   console.log(buf.toString('hex'))
  // })
  var stream = fs.createReadStream(filename)
  stream.on('data', function(chunk) {
    md5sum.update(chunk)
  })
  stream.on('end', function() {
    str = md5sum.digest('hex').toUpperCase()
    console.log(
      '文件:' +
        filename +
        ',MD5签名为:' +
        str +
        '.耗时:' +
        (new Date().getTime() - start) / 1000.0 +
        '秒'
    )
    fs.rename(filename, 'img/' + str + '.jpg', function(err) {
      if (err) {
        console.log('重命名失败！')
      } else {
        console.log('重命名成功！')
      }
    })
  })
}

var i = 0

function _getVImg(detailUrl) {
  console.log('start get Image: ' + detailUrl)

  // var sched = later.parse.text('every 1 seconds')
  // console.log(sched.schedules[0].s.toString())

  // // 设定为本地时间
  // later.date.localTime()
  // later.setInterval(function(_detailUrl) {
  //   var imgName = 'img/test' + i + '.jpg'
  //   i++
  //   if (i < 3600) {
  //     var stream = fs.createWriteStream(imgName)
  //     var req = request
  //       .get(detailUrl)
  //       .set(headers)
  //       .set({ Cookie: ShopCookie })
  //     req.pipe(stream)
  //     stream.on('finish', function() {
  //       _rename(imgName)
  //     })
  //   } else {
  //     console.log('图片获取完成!')
  //     return
  //   }
  // }, sched)
}

function _getRealVImg(detailUrl) {
  console.log('start get Real Image: ' + detailUrl)
  console.log(ShopCookie)
  var _shopCookie = []
  // console.log(ShopCookie)
  for (x in ShopCookie) {
    // console.log(ShopCookie[x])
    var _arr = ShopCookie[x].split(';')
    // console.log(_arr[0])
    _shopCookie.push(_arr[0])
  }
  console.log(_shopCookie)
  ShopCookie = _shopCookie

  var req = request
    .get(detailUrl)
    .set(headers)
    .set({ Cookie: _shopCookie })
    .redirects(0) // 防止页面重定向
    .end(function(err, res) {
      console.log('URL: ' + res.request.url)
      _detailUrl = res.headers.location
      console.log('Real URL: ' + _detailUrl)
      console.log('status: ' + res.status)
      console.log(res.body)

      console.log('-------------------------------------\n\n\n')
      // var i = 0
      // task({ s: [] }, function() {
      _getVImg(_detailUrl)
      // })
    })
}

function _Login(account, _xsrf, lt, service) {
  var that = this
  // 登录
  console.log('start login')
  console.log(JSON.stringify(account))
  var detailUrl = ''
  request
    .post(urls.login)
    .set(headers)
    .set('Cookie', LoginCookie)
    .type('form')
    .send({
      username: account.user,
      password: account.password,
      lt: lt,
      service: service,
      _xsrf: _xsrf
    })
    .redirects(0) // 防止页面重定向
    .end(function(err, res) {
      console.log('URL: ' + res.request.url)
      detailUrl = res.headers.location
      console.log('Real URL: ' + detailUrl)
      console.log('login status: ' + res.status)
      LoginCookie.concat(err.response.headers['set-cookie'])
      console.log('login cookie: ' + LoginCookie)

      console.log('-------------------------------------\n\n\n')

      _getRealVImg(detailUrl)
    })
}

function Login(account) {
  var that = this

  //获取shop的cookie

  console.log('get shop cookie')

  var loginLocation = ''
  request
    .get(shopurl)
    .set(headers)
    .set({ Cookie: ShopCookie })
    .end(function(err, res) {
      ShopCookie = res.headers['set-cookie']
      console.log(ShopCookie)
      request
        .get(urls.validateImg)
        .set(headers)
        // .set({ Referer: 'https://shop.bitmain.com/' })
        // .set({ Host: 'shop.bitmain.com' })
        .set({ Cookie: ShopCookie })
        .end(function(err, res) {
          console.log('URL: ' + res.request.url)
          LoginCookie = err.response.headers['set-cookie']
          console.log('LoginCookie: ' + LoginCookie)
          var $ = cheerio.load(err.response.text)
          _xsrf = $('[name="_xsrf"]').val()
          console.log('_xsrf: ' + _xsrf)
          lt = $('[name="lt"]').val()
          console.log('lt: ' + lt)
          service = $('[name="service"]').val()
          console.log('service: ' + service)

          // 回调登录
          _Login(account, _xsrf, lt, service)
        })
    })
}

accounts.forEach(function(v) {
  Login(v)
})
